package org.idea.qiyu.framework.threadpool.core;

import java.util.LinkedList;

/**
 * @Author linhao
 * @Date created in 8:57 上午 2021/10/14
 */
public class LinkedRunnableQueue implements RunnableQueue {

    private LinkedList<Runnable> taskList = new LinkedList<>();

    private ThreadPool threadPool;

    private int maxSize;

    private DenyPolicy denyPolicy;

    @Override
    public void offer(Runnable runnable) {
        synchronized (taskList) {
            if (taskList.size() > maxSize) {
                denyPolicy.reject(runnable, threadPool);
            }
            taskList.addFirst(runnable);
            taskList.notifyAll();
        }
    }

    @Override
    public Runnable take() {
        synchronized (taskList) {
            while (taskList.isEmpty()) {
                try {
                    taskList.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return taskList.removeFirst();
    }

    @Override
    public int size() {
        synchronized (taskList) {
            return taskList.size();
        }
    }
}
